import 'package:fixnum/fixnum.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

// import 'package:get/get_connect/http/src/response/response.dart'
//     as get_response;
import 'package:im_demo/app/services/websocket_service_protobuf.dart';

import '../../../../core/protos/v1/chat.pb.dart' as chat_proto;
import '../../../../utils/logger_util.dart';

class RegisterController extends GetxController {
  var urlEditController = TextEditingController();
  var userNameEditController = TextEditingController();
  var passwordEditController = TextEditingController();
  var phoneNumberEditController = TextEditingController();
  var wechatNumberEditController = TextEditingController();
  var remarksEditController = TextEditingController();

  static const defaultUrl = 'ws://192.168.1.100:8090/ws';
  static const token = '';

  final messageList = <chat_proto.ChatMessage>[].obs;

  @override
  void onInit() {
    super.onInit();

    Get.put(WebSocketServiceProtobuf());
  }

  @override
  void onReady() {
    super.onReady();

    updateUrlInputText(defaultUrl);
  }

  @override
  void onClose() {
    _disconnectWebsocket();
    super.onClose();
  }

  void updateUrlInputText(String text) {
    _updateUrlInputText(urlEditController, text);
  }

  void cleanUrlInputText() {
    _cleanInputText(urlEditController);
  }

  void updateUserNameInputText(String text) {
    _updateUrlInputText(userNameEditController, text);
  }

  void cleanUserNameInputText() {
    _cleanInputText(urlEditController);
  }

  void updatePasswordInputText(String text) {
    _updateUrlInputText(passwordEditController, text);
  }

  void cleanPasswordInputText() {
    _cleanInputText(passwordEditController);
  }

  void updatePhoneNumberInputText(String text) {
    _updateUrlInputText(phoneNumberEditController, text);
  }

  void cleanPhoneNumberInputText() {
    _cleanInputText(phoneNumberEditController);
  }

  void updateWechatNumberInputText(String text) {
    _updateUrlInputText(wechatNumberEditController, text);
  }

  void cleanWechatNumberInputText() {
    _cleanInputText(wechatNumberEditController);
  }

  void updateRemarksInputText(String text) {
    _updateUrlInputText(remarksEditController, text);
  }

  void cleanRemarksInputText() {
    _cleanInputText(remarksEditController);
  }

  void _cleanInputText(TextEditingController editingController) {
    editingController.clear();
  }

  void _updateUrlInputText(
    TextEditingController editingController,
    String text,
  ) {
    editingController.text = text;
  }

  void connectWebsocket() {
    _connectWebsocket();
  }

  void _connectWebsocket() async {
    final startConnectMessage =
        chat_proto.ChatMessage()
          ..type = chat_proto.MessageType.UNKNOWN
          ..token = ''
          ..sender = Int64.parseInt('-1')
          ..receiver = Int64.parseInt('-1')
          ..groupId = Int64.parseInt('-1')
          ..content = '开始连接,请稍等...';

    _addMessage(startConnectMessage);

    final url =
        urlEditController.text.isEmpty ? defaultUrl : urlEditController.text;
    logE('_connectWebsocket url:$url');

    await WebSocketServiceProtobuf.to.connect(url, token);

    if (WebSocketServiceProtobuf.to.isConnected.value) {
      final connectMessage =
          chat_proto.ChatMessage()
            ..type = chat_proto.MessageType.UNKNOWN
            ..token = ''
            ..sender = Int64.parseInt('-1')
            ..receiver = Int64.parseInt('-1')
            ..groupId = Int64.parseInt('-1')
            ..content = '已连接';

      _addMessage(connectMessage);
    }

    _setupWebSocket();
  }

  void disconnectWebsocket() {
    _disconnectWebsocket();
  }

  void _disconnectWebsocket() {
    WebSocketServiceProtobuf.to.disconnect();

    final message =
        chat_proto.ChatMessage()
          ..type = chat_proto.MessageType.UNKNOWN
          ..token = ''
          ..sender = Int64.parseInt('-1')
          ..receiver = Int64.parseInt('-1')
          ..groupId = Int64.parseInt('-1')
          ..content = '已断开连接';
    _addMessage(message);
  }

  void _setupWebSocket() {
    WebSocketServiceProtobuf.to.stream.listen(
      (data) {
        logE('_setupWebSocket()-->data:$data');

        chat_proto.MessageWrapper messageWrapper = chat_proto
            .MessageWrapper.fromBuffer(data);
        logE('_setupWebSocket()-->messageWrapper:$messageWrapper');

        _handlerMessage(messageWrapper);
      },
      onDone: () => _disconnectWebsocket(),
      onError: (err) {
        logE('_setupWebSocket()-->onError:$err');

        _disconnectWebsocket();
      },
    );
  }

  void _handlerMessage(chat_proto.MessageWrapper messageWrapper) {
    switch (messageWrapper.type) {
      case chat_proto.MessageType.REGISTER:
        final chat_proto.Response registerResponse = chat_proto
            .Response.fromBuffer(messageWrapper.payload);

        logE('_handlerMessage()-->registerResponse:$registerResponse');

        String msg = '';
        if (registerResponse.success) {
          msg = '注册成功';
        } else {
          msg = '注册失败！${registerResponse.message}';
        }

        final registerMessage =
            chat_proto.ChatMessage()
              ..type = chat_proto.MessageType.UNKNOWN
              ..token = ''
              ..sender = Int64.parseInt('-1')
              ..receiver = Int64.parseInt('-1')
              ..groupId = Int64.parseInt('-1')
              ..content = msg;

        _addMessage(registerMessage);
        break;
      case chat_proto.MessageType.LOGIN:
        break;
      case chat_proto.MessageType.LOGOUT:
        break;
      case chat_proto.MessageType.PRIVATE_CHAT:
        break;
      case chat_proto.MessageType.GROUP_CHAT:
        break;
      default:
        break;
    }
  }

  void _addMessage(chat_proto.ChatMessage message) {
    messageList.insert(0, message);
  }

  void register() {
    final String userName = userNameEditController.text.trim();
    if (userName.isEmpty) {
      Get.snackbar('温馨提示', '请输入用户名');
      return;
    }

    final String pwd = passwordEditController.text.trim();
    final String phone = phoneNumberEditController.text.trim();
    final String wechatId = wechatNumberEditController.text.trim();
    final String remarks = remarksEditController.text.trim();

    chat_proto.RegisterRequest registerRequest = chat_proto.RegisterRequest(
      username: userName,
      password: pwd,
      phoneNumber: phone,
      wechatNumber: wechatId,
      remarks: remarks,
    );

    chat_proto.MessageWrapper wrapper = chat_proto.MessageWrapper(
      type: chat_proto.MessageType.REGISTER,
      payload: registerRequest.writeToBuffer(),
    );

    WebSocketServiceProtobuf.to.sendMessage(wrapper.writeToBuffer());

    final message =
        chat_proto.ChatMessage()
          ..type = chat_proto.MessageType.UNKNOWN
          ..token = ''
          ..sender = Int64.parseInt('-1')
          ..receiver = Int64.parseInt('-1')
          ..groupId = Int64.parseInt('-1')
          ..content = '正在注册,请稍等...';

    _addMessage(message);
  }
}
